﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;

namespace KJFrame.Core.CapDemo.Controllers
{
    /// <summary>
    /// 测试回调
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TransactionDemoController : Controller
    {
        private readonly ICapPublisher _capBus;

        public TransactionDemoController(ICapPublisher capPublisher)
        {
            _capBus = capPublisher;
        }

        public string Index()
        {
            return "Hello word";
        }

        /// <summary>
        /// 手动提交事务
        /// </summary>
        /// <returns></returns>
        [HttpGet("~/send")]
        public async Task<IActionResult> TestCallback()
        {
            using (var connnection = new SqlConnection("Integrated Security=False;server=192.168.1.109;database=cap;User ID=sa;Password=198603yang;Connect Timeout=30"))
            {
                using (var transaction = connnection.BeginTransaction(_capBus, false))
                {
                    var sql = "update UserTransaction set Name='嘻嘻' where id=1";
                    connnection.Execute(sql, null, transaction);
                    await _capBus.PublishAsync("kjframe.test5", DateTime.Now);
                    transaction.Commit();
                    return Content("服务端send");
                }
            }
        }

        /// <summary>
        /// 自动提交事务
        /// </summary>
        /// <returns></returns>
        [HttpGet("~/send2")]
        public async Task<IActionResult> SendTransaction()
        {
            using (var connnection = new SqlConnection("Integrated Security=False;server=192.168.1.109;database=cap;User ID=sa;Password=198603yang;Connect Timeout=30"))
            {
                using (var transaction = connnection.BeginTransaction(_capBus, true))
                {
                    var sql = "update UserTransaction set Name='hahahah' where id=1";
                    connnection.Execute(sql, null, transaction);
                    await _capBus.PublishAsync("kjframe.test5", DateTime.Now);
                    return Content("服务端send");
                }
            }
        }

    }
}
